package net.asfun.jvalog.domain;

import java.util.Collection;

import javax.jdo.Query;

import net.asfun.jvalog.po.Label;
import net.asfun.jvalog.po.Meter;
import net.asfun.jvalog.po.Paper;
import net.asfun.jvalog.po.Sort;
import net.asfun.jvalog.service.Jdoer;
import net.asfun.jvalog.service.JdoerFactory;

import com.google.appengine.api.datastore.Key;

public class Counter {
	
	protected static int getCount(Key owner) {
		Jdoer<Meter> dbm = JdoerFactory.getMeterJdo();
		Query q = dbm.prepareQuery();
		q.setFilter("owner == mykey");
		q.declareParameters("com.google.appengine.api.datastore.Key mykey");
		Meter meter =  dbm.unique(q, owner);
		if ( meter == null ) return 0;
		return meter.getCount();
	}
	
	private static void setCount(Key owner, int number) {
		Jdoer<Meter> dbm = JdoerFactory.getMeterJdo();
		Query q = dbm.prepareQuery();
		q.setFilter("owner == mykey");
		q.declareParameters("com.google.appengine.api.datastore.Key mykey");
		Meter meter =  dbm.unique(q, owner);
		if ( meter == null) {
			meter = new Meter();
			meter.setCount(number);
			meter.setOwner(owner);
			dbm.save(meter);
		} else {
			meter.setCount(number);
		}
	}
	
	public static void rebuild() {
		//count posts in each tag
		Jdoer<Label> dbl = JdoerFactory.getLabelJdo();
		Collection<Label> clt = dbl.all();
		for(Label label : clt ) {
			setCount(label.getKey(), Bridge.getRelationsByRight(label.getKey(), Bridge.POST_TAG).size());
		}
		//count posts in each category
		Jdoer<Sort> dbs = JdoerFactory.getSortJdo();
		Collection<Sort> clt1 = dbs.all();
		for(Sort sort : clt1 ) {
			setCount(sort.getKey(), Bridge.getRelationsByRight(sort.getKey(), Bridge.POST_CATEGORY).size());
		}
		//count comments in each post
		Jdoer<Paper> dbp = JdoerFactory.getPaperJdo();
		Query q = dbp.prepareQuery();
		q.setFilter("type == 0 && published == true");
		Collection<Paper> clt2 = dbp.more(q);
		for(Paper paper : clt2 ) {
			setCount(paper.getKey(), Bridge.getRelationsByLeft(paper.getKey(), Bridge.POST_COMMENT).size());
		}
	}
}
